package bh

import android.content.Context
import android.graphics.drawable.Drawable
import yyee.llee.mmee.common.R
import bh.FS.getNowHour

object FU {


    @JvmStatic
    fun getDayIcon(context: Context, weatherCode: String): Drawable? {
        return getIcon(context, weatherCode, "d")
    }

    private fun getIcon(context: Context, weatherCode: String, postFix: String): Drawable? {
        val convertCode = GC.convertCode(weatherCode)
        val code = parseCode(convertCode.toString(), postFix)
        val resName = "icon_$code"
        val resId = getDrawableRes(context, resName, R.mipmap.icon_0d)
        return context.resources.getDrawable(resId, null)
    }

    private fun parseCode(weather: String, postFix: String): String {
        val code = (if (weather.isEmpty()) "0" else weather).toInt()
        return if (isDay()) {
            code.toString() + postFix
        } else {
            when (code) {
                0, 1, 3 -> {
                    code.toString() + "n"
                }

                else -> {
                    code.toString() + postFix
                }
            }
        }
    }

    @JvmStatic
    fun isDay(): Boolean {
        val now = getNowHour()
        return now in 7..18
    }

    /**
     * 获取白天背景
     */
    val defaultBg: Int
        get() = if (isDay()) R.mipmap.bg_0_d else R.mipmap.bg_0_n

    /**
     * 获取背景
     */
    fun getBg(context: Context, code: Int): Int {
        return if (isDay()) getDayBg(context, code) else getNightBg(context, code)
    }

    /**
     * 获取白天背景
     */
    private fun getDayBg(context: Context, code: Int): Int {
        var newCode = code
        return getDrawableRes(context, "bg_" + newCode + "_d", R.mipmap.bg_0_d)
    }

    /**
     * 获取晚上背景
     */
    private fun getNightBg(context: Context, code: Int): Int {
        var newCode = code
        return getDrawableRes(context, "bg_" + newCode + "_d", R.mipmap.bg_0_d)
    }

    private fun getDrawableRes(context: Context, weather: String, def: Int): Int {
        return getRes(context, "mipmap", weather, def)
    }

    private fun getRes(context: Context, type: String?, weather: String, def: Int): Int {
        return try {
            var id = context.resources.getIdentifier(weather, type, context.packageName)
            if (id == 0) {
                id = def
            }
            id
        } catch (e: Exception) {
            def
        }
    }
}